/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.digitalization.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.constant.LogConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.oss.ArchiveMinioTemplate;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.digitalization.entity.A01Entity;
import org.springblade.modules.digitalization.entity.A02Entity;
import org.springblade.modules.digitalization.entity.DigitPinyinEntity;
import org.springblade.modules.digitalization.entity.UmsUserInfoEntity;
import org.springblade.modules.digitalization.excel.A01Excel;
import org.springblade.modules.digitalization.manager.LogManager;
import org.springblade.modules.digitalization.mapper.A01Mapper;
import org.springblade.modules.digitalization.mapper.UmsUserInfoMapper;
import org.springblade.modules.digitalization.service.IA01Service;
import org.springblade.modules.digitalization.service.IA02Service;
import org.springblade.modules.digitalization.service.IDigitPinyinService;
import org.springblade.modules.digitalization.utils.DaUtils;
import org.springblade.modules.digitalization.vo.A01VO;
import org.springblade.modules.digitalization.wrapper.UserInfoRs;
import org.springblade.modules.system.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 人员基本信息集 服务实现类
 *
 * @author BladeX
 * @since 2022-10-18
 */
@Slf4j
@Service
public class A01ServiceImpl extends BaseServiceImpl<A01Mapper, A01Entity> implements IA01Service {

	@Autowired
	private IDictService dictService;
	@Autowired
	private UmsUserInfoMapper umsUserInfoMapper;
	@Resource
	private IDigitPinyinService digitPinyinService;
	@Resource
	private IA02Service ia02Service;
	@Autowired
	private LogManager logManager;
	@Autowired
	private ArchiveMinioTemplate a01ArchiveTemplate;

	@Transactional
	@Override
	public boolean deleteByIds(List<Long> ids) {
		log.info("删除人员信息:{}", JSON.toJSONString(ids));
		List<A01Entity> oldDatas = this.listByIds(ids);
		boolean b = this.deleteLogic(ids);
		oldDatas.forEach(item -> {
			logManager.doDel(item.getA0000(), LogManager.TYPE_A01, item);
			a01ArchiveTemplate.removeDir(item.getA0000());
		});
		return b;
	}

	@Override
	public IPage<A01VO> selectA01Page(IPage<A01VO> page, A01VO a01) {
		return page.setRecords(baseMapper.selectA01Page(page, a01));
	}

	@Override
	public List<A01Excel> exportA01(Wrapper<A01Entity> queryWrapper) {
		List<A01Excel> a01List = baseMapper.exportA01(queryWrapper);
		//a01List.forEach(a01 -> {
		//	a01.setTypeName(DictCache.getValue(DictEnum.YES_NO, A01.getType()));
		//});
		return a01List;
	}

	@Override
	public UserInfoRs getUserInfoBy(Long id) {
		UmsUserInfoEntity byId = umsUserInfoMapper.selectById(id);
		UserInfoRs userInfoRs = new UserInfoRs();
		userInfoRs.setUserName(byId.getA0101());
		userInfoRs.setId(byId.getA0000());
		userInfoRs.setIdCard(byId.getA0184());
		userInfoRs.setBirthDay(byId.getA0107());
		String a0117 = StringUtils.leftPad(byId.getA0117(), 2, "0");
		userInfoRs.setMz(dictService.getValue("GB3304", a0117));
		userInfoRs.setSex(dictService.getValue("GB2261", byId.getA0104()));
		userInfoRs.setA0141(dictService.getValue("GB4762", byId.getA0141()));
		userInfoRs.setA0111a(byId.getA0111a());
		userInfoRs.setA0192(byId.getA0192());

		userInfoRs.setDwmc(byId.getA0201a());
		userInfoRs.setDwdm(byId.getA0201b());
		userInfoRs.setDwzh(byId.getTenantId());
		return userInfoRs;
	}

	@Override
	public List<UserInfoRs> getAllUserInfoByStatus(int status) {
		List<UmsUserInfoEntity> umsUserInfoEntities = umsUserInfoMapper.selectList(Wrappers.<UmsUserInfoEntity>lambdaQuery().eq(UmsUserInfoEntity::getStatus, status));
		List<UserInfoRs> collect = umsUserInfoEntities.stream().map(this::convertToUserInfoRs).collect(Collectors.toList());
		return collect;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveOrUpdateA01(A01Entity newData) {

		if (Func.isNotEmpty(newData.getA0195())) {
			boolean update1 = ia02Service.update(Wrappers.<A02Entity>lambdaUpdate().eq(A02Entity::getA0000, newData.getA0000()).set(A02Entity::getA0201b, newData.getA0195()));
			if (!update1) {
				throw new ServiceException("更新机构失败");
			}
		}

		A01Entity oldObject = this.getById(newData.getId());

		if (saveOrUpdate(newData)) {
			// 存在旧数据，代表更新
			if (oldObject != null) {
				logManager.doUpdate(newData.getA0000(), LogManager.TYPE_A01, oldObject, newData);
			} else {
				logManager.doAdd(newData.getA0000(), LogManager.TYPE_A01, newData);
			}
			DigitPinyinEntity digitPinyinEntity = digitPinyinService.getOne(Wrappers.<DigitPinyinEntity>lambdaQuery().eq(DigitPinyinEntity::getOrgId, newData.getId()), false);
			if (Func.isEmpty(digitPinyinEntity)) {
				digitPinyinEntity = new DigitPinyinEntity();
				digitPinyinEntity.setOrgId(newData.getId());
				digitPinyinEntity.setTableType("A01@A0101");
			}
			digitPinyinEntity.setSourceData(newData.getA0101());
			digitPinyinEntity.setPinyin(PinyinUtil.getPinyin(newData.getA0101(), "") + " " + PinyinUtil.getFirstLetter(newData.getA0101(), ""));
			if (digitPinyinService.saveOrUpdate(digitPinyinEntity) == false) {
				throw new ServiceException("拼音更新失败");
			}
		} else {
			throw new ServiceException("更新人员信息失败");
		}
		return true;
	}

	@Override
	public List<A01Entity> getByA0000AndStatus(List<String> a0000List, int status) {
		List<A01Entity> list = list(Wrappers.<A01Entity>lambdaQuery()
			.eq(A01Entity::getStatus, status)
			.in(A01Entity::getA0000, a0000List)
		);
		return list;
	}

	@Override
	public List<A01Entity> getByA0195AndStatus(String a0195, int status) {
		List<A01Entity> list = list(Wrappers.<A01Entity>lambdaQuery()
			.eq(A01Entity::getStatus, status)
			.likeLeft(A01Entity::getA0195, a0195)
		);
		return list;
	}

	@Override
	public List<A01Entity> getByA0000(List<String> a0000List) {
		List<A01Entity> list = list(Wrappers.<A01Entity>lambdaQuery()
			.in(A01Entity::getA0000, a0000List)
		);
		return list;
	}

	@Override
	public A01Entity getByA0000(String a0000) {
		A01Entity one = getOne(Wrappers.<A01Entity>lambdaQuery().eq(A01Entity::getA0000, a0000));
		return one;
	}

	@Override
	public UserInfoRs getUserInfoByArchiveId(String a0000) {
		UmsUserInfoEntity userInfoEntity = umsUserInfoMapper.selectOne(Wrappers.<UmsUserInfoEntity>lambdaQuery().eq(UmsUserInfoEntity::getA0000, a0000));
		UserInfoRs userInfoRs = convertToUserInfoRs(userInfoEntity);
		return userInfoRs;
	}


	private UserInfoRs convertToUserInfoRs(UmsUserInfoEntity umsUserInfoEntity) {

		UserInfoRs userInfoRs = new UserInfoRs();
		userInfoRs.setOrgId(umsUserInfoEntity.getId());
		userInfoRs.setUserName(umsUserInfoEntity.getA0101());
		userInfoRs.setId(umsUserInfoEntity.getA0000());
		userInfoRs.setIdCard(umsUserInfoEntity.getA0184());
		userInfoRs.setBirthDay(umsUserInfoEntity.getA0107());
		String a0117 = StringUtils.leftPad(umsUserInfoEntity.getA0117(), 2, "0");
		userInfoRs.setMz(dictService.getValue("GB3304", a0117));
		userInfoRs.setSex(dictService.getValue("GB2261", umsUserInfoEntity.getA0104()));
		userInfoRs.setA0141(dictService.getValue("GB4762", umsUserInfoEntity.getA0141()));
		userInfoRs.setA0111a(umsUserInfoEntity.getA0111a());
		userInfoRs.setA0192(umsUserInfoEntity.getA0192());

		userInfoRs.setDwmc(umsUserInfoEntity.getA0201a());
		userInfoRs.setDwdm(umsUserInfoEntity.getA0201b());
		userInfoRs.setDwzh(umsUserInfoEntity.getTenantId());
		return userInfoRs;
	}


}
